import Axios from 'axios'
import { Message } from 'element-ui';
import { server } from './globalVariables.js'
/**
 * @param {string} urlName 请求路径
 * @param {string} type 请求类型
 * @param {string} headersObj 请求头
 * @param {string} params get请求的请求参数
 * @param {string} formData post请求的时候请求的参数
 * @param {function} fun 接口请求成功时的回调函数
 * @param {function} failFun 接口请求失败时的回调函数
 */
export function axiosFun(urlName, type, headersObj, params, formData, fun, failFun) {
  !type ? type = 'post' : type = type.toLowerCase();
  !headersObj ? headersObj = {} : '';
  let config = {
    method: type,
    baseURL: server,
    url: urlName,
    data: formData,
    params: params,
    headers: headersObj,
  };
  let token = window.sessionStorage.getItem('loginMsg');
  if (token) {
    config.headers.Authorization = token;
  }
  Axios(config).then(success => {
    let resData = success.data;
    if (!resData.state.code) {
      fun(resData);
    } else {
      failFun(resData);
    }
  }).catch(err => {
    // console.log("err:",err.response);
    if( err.response ){
      err.response.status === 401
      ?
      (()=>{
        console.log(err.response.status);
        this.$router.push({
          name: "login"
        });
      })()
      :"";
    }
    // console.log(err);
    // console.log(urlName);
    // Message.error('请求失败,请稍后再试');
  })
}
